/********************************************************************************
* File Name:	mainwindow.cpp
* Description:	第3章 实例6：TreeView的实例
* Reference book:《Linux环境下Qt4图形界面与MySQL编程》，机械工业出版社.2012.1
* E_mail: openlinux2011@gmail.com
*
********************************************************************************/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QModelIndex>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->treeView->header()->setResizeMode(QHeaderView::ResizeToContents);

    model = new QStandardItemModel(4,1);
    model->setHeaderData(0, Qt::Horizontal, tr("First"));
    //model->setHeaderData(1, Qt::Horizontal, tr("Second"));

    QStandardItem *item1 = new QStandardItem("item1");
    QStandardItem *item2 = new QStandardItem("item2");
    QStandardItem *item3 = new QStandardItem("item3");
    QStandardItem *item4 = new QStandardItem("item4");
    model->setItem(0, 0, item1);
    model->setItem(1, 0, item2);
    model->setItem(2, 0, item3);
    model->setItem(3, 0, item4);

    QStandardItem *item5 = new QStandardItem("item5");
    item4->appendRow(item5);
    QStandardItem *item6 = new QStandardItem("item6");
    item5 ->appendRow(item6);
    QModelIndex modelIndex;
    for (int i = 0; i < 4; ++i)
    {
       modelIndex = model->index(0, 0, modelIndex);
       model->insertRows(0, 1, modelIndex);
       model->insertColumns(0, 1, modelIndex);
       QModelIndex index = model->index(0, 0, modelIndex);
       model->setData(index, i);
    }
    ui->treeView->setModel(model);

    iterateOverItems();
}

MainWindow::~MainWindow()
{
    delete ui;
}
QList<QStandardItem*> MainWindow::returnTheItems()
{
    return model->findItems("*", Qt::MatchWildcard | Qt::MatchRecursive);
}
void MainWindow::iterateOverItems()
{
    QList<QStandardItem*> list = returnTheItems();
    foreach (QStandardItem* item, list)
    {
        ui->textEdit->setText(ui->textEdit->toPlainText()+item->text()+"\n");
    }
}
//void MainWindow::mouseDoubleClickEvent(QMouseEvent *event)
//{
//    if (event->button() == Qt::LeftButton)
//    {
//        QModelIndex index0 = ui->treeView->currentIndex();
//        qDebug() << index0.data().toString();
//    }
//}

void MainWindow::on_treeView_doubleClicked(QModelIndex index)
{
    QModelIndex index0 = ui->treeView->currentIndex();
    ui->textEdit_2->append(index0.data().toString()+" is CurrentItem!");
}
